<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\exception\UploadException;
use app\common\library\Upload;
use app\common\model\Area;
use app\common\model\Version;
use fast\Random;
use think\captcha\Captcha;
use think\Config;
use think\Hook;

/**
 * 公共接口
 * @ApiWeigh (100)
 */
class Common extends Api
{
    protected $noNeedLogin = ['init', 'captcha','getContent','getKefuInfo'];
    protected $noNeedRight = '*';

    public function _initialize()
    {

        if (isset($_SERVER['HTTP_ORIGIN'])) {
            header('Access-Control-Expose-Headers: __token__');//跨域让客户端获取到
        }
        //跨域检测
        check_cors_request();

        if (!isset($_COOKIE['PHPSESSID'])) {
            Config::set('session.id', $this->request->server("HTTP_SID"));
        }
        parent::_initialize();
    }

    /**
     * 加载初始化
     * 用于APP启动时获取基础配置信息，包括城市定位、版本检查、上传配置等
     * 
     * @ApiTitle    (初始化接口)
     * @ApiSummary  (获取APP基础配置信息)
     * @ApiMethod   (GET)
     * @ApiParams   (name="version", type="string", required=true, description="APP版本号")
     * @ApiParams   (name="lng", type="string", required=true, description="经度")
     * @ApiParams   (name="lat", type="string", required=true, description="纬度")
     * @ApiReturn   ({
     *   "code": 1,
     *   "msg": "",
     *   "data": {
     *     "citydata": {             // 城市定位信息
     *       "id": "1",              // 城市ID
     *       "name": "北京市",       // 城市名称
     *       "pid": "0",             // 上级ID
     *       "level": "1"            // 城市级别:1=省,2=市,3=区
     *     },
     *     "versiondata": {          // 版本信息
     *       "version": "1.0.0",     // 最新版本号
     *       "downloadurl": "",      // 下载地址
     *       "updatetime": "",       // 更新时间
     *       "content": "",          // 更新内容
     *       "enforce": 0            // 是否强制更新:0=否,1=是
     *     },
     *     "uploaddata": {           // 上传配置
     *       "cdnurl": "",          // CDN地址
     *       "uploadurl": "",       // 上传接口地址
     *       "bucket": "",          // 存储空间
     *       "maxsize": "10mb",     // 最大上传大小
     *       "mimetype": "",        // 允许的文件类型
     *       "multipart": []        // 分片上传配置
     *     },
     *     "coverdata": {           // 封面配置
     *       "default": ""          // 默认封面
     *     }
     *   }
     * })
     */
    public function init()
    {
        if ($version = $this->request->request('version')) {
            $lng = $this->request->request('lng');
            $lat = $this->request->request('lat');

            //配置信息
            $upload = Config::get('upload');
            //如果非服务端中转模式需要修改为中转
            if ($upload['storage'] != 'local' && isset($upload['uploadmode']) && $upload['uploadmode'] != 'server') {
                //临时修改上传模式为服务端中转
                set_addon_config($upload['storage'], ["uploadmode" => "server"], false);

                $upload = \app\common\model\Config::upload();
                // 上传信息配置后
                Hook::listen("upload_config_init", $upload);

                $upload = Config::set('upload', array_merge(Config::get('upload'), $upload));
            }

            $upload['cdnurl'] = $upload['cdnurl'] ? $upload['cdnurl'] : cdnurl('', true);
            $upload['uploadurl'] = preg_match("/^((?:[a-z]+:)?\/\/)(.*)/i", $upload['uploadurl']) ? $upload['uploadurl'] : url($upload['storage'] == 'local' ? '/api/common/upload' : $upload['uploadurl'], '', false, true);

            $content = [
                'citydata'    => Area::getCityFromLngLat($lng, $lat),
                'versiondata' => Version::check($version),
                'uploaddata'  => $upload,
                'coverdata'   => Config::get("cover"),
            ];
            $this->success('', $content);
        } else {
            $this->error(__('Invalid parameters'));
        }
    }

    /**
     * 上传文件
     * 支持普通上传和分片上传两种方式，可用于处理大文件上传
     * 
     * @ApiTitle    (文件上传接口)
     * @ApiSummary  (处理文件上传请求，支持普通上传和分片上传)
     * @ApiMethod   (POST)
     * @ApiParams   (name="file", type="file", required=true, description="上传的文件")
     * @ApiParams   (name="chunkid", type="string", required=false, description="分片上传的文件标识")
     * @ApiParams   (name="chunkindex", type="integer", required=false, description="当前分片索引")
     * @ApiParams   (name="chunkcount", type="integer", required=false, description="分片总数")
     * @ApiParams   (name="filename", type="string", required=false, description="原始文件名")
     * @ApiParams   (name="action", type="string", required=false, description="分片上传动作:merge=合并分片,clean=清理分片")
     * @ApiReturn   ({
     *   "code": 1,
     *   "msg": "上传成功",
     *   "data": {
     *     "url": "/uploads/xxx.jpg",     // 文件相对路径
     *     "fullurl": "http://xxx.com/uploads/xxx.jpg"  // 文件完整访问路径
     *   }
     * })
     */
    public function upload()
    {
        Config::set('default_return_type', 'json');
        //必须设定cdnurl为空,否则cdnurl函数计算错误
        Config::set('upload.cdnurl', '');
        $chunkid = $this->request->post("chunkid");
        if ($chunkid) {
            if (!Config::get('upload.chunking')) {
                $this->error(__('Chunk file disabled'));
            }
            $action = $this->request->post("action");
            $chunkindex = $this->request->post("chunkindex/d");
            $chunkcount = $this->request->post("chunkcount/d");
            $filename = $this->request->post("filename");
            $method = $this->request->method(true);
            if ($action == 'merge') {
                $attachment = null;
                //合并分片文件
                try {
                    $upload = new Upload();
                    $attachment = $upload->merge($chunkid, $chunkcount, $filename);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $this->success(__('Uploaded successful'), ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)]);
            } elseif ($method == 'clean') {
                //删除冗余的分片文件
                try {
                    $upload = new Upload();
                    $upload->clean($chunkid);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $this->success();
            } else {
                //上传分片文件
                //默认普通上传文件
                $file = $this->request->file('file');
                try {
                    $upload = new Upload($file);
                    $upload->chunk($chunkid, $chunkindex, $chunkcount);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $this->success();
            }
        } else {
            $attachment = null;
            //默认普通上传文件
            $file = $this->request->file('file');
            try {
                $upload = new Upload($file);
                $attachment = $upload->upload();
            } catch (UploadException $e) {
                $this->error($e->getMessage());
            } catch (\Exception $e) {
                $this->error($e->getMessage());
            }

            $this->success(__('Uploaded successful'), ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)]);
        }

    }

    /**
     * 验证码
     * @ApiInternal
     * @ApiParams (name="id", type="string", required=true, description="要生成验证码的标识")
     * @return \think\Response
     */
    public function captcha($id = "")
    {
        \think\Config::set([
            'captcha' => array_merge(config('captcha'), [
                'fontSize' => 44,
                'imageH'   => 150,
                'imageW'   => 350,
            ])
        ]);
        $captcha = new Captcha((array)Config::get('captcha'));
        return $captcha->entry($id);
    }

    /**
     * 获取内容配置信息
     * @ApiParams (name="type", type="string", required=true, description="配置类型:user_agreement=用户协议,about_us=关于我们")
     */
    public function getContent()
    {
        $type = $this->request->request('type');
        $allowTypes = ['user_agreement', 'about_us','privacy_policy'];
        
        if (!in_array($type, $allowTypes)) {
            $this->error('不支持的配置类型');
        }
        
        $content = \think\Db::name('config')
            ->where('name', $type)
            ->value('value');
            
        if ($content) {
            $this->success('获取成功', ['content' => $content]);
        } else {
            $this->error('配置不存在');
        }
    }
    /**
     * 获取客服配置信息
     * @ApiParams
     */
    public function getKefuInfo()
    {
        $kefu_url = \think\Db::name('config')
            ->where('name', 'kefu_url')
            ->value('value');
        $work_appid = \think\Db::name('config')
            ->where('name', 'work_appid')
            ->value('value'); 
        $this->success('获取成功', ['kefu_url' => $kefu_url,'work_appid' => $work_appid]);
    }
    /**
     * 注册IM用户信息
     * @ApiInternal
     * @ApiMethod (POST)
     */
    public function addImUser($user_id,$nickname = '',$image = ''){
        $tenApi = new TLSSigAPIv2();
        $im_user_sig = $tenApi->genUserSig("administrator");
        $random = random_int(1, 9999);
        $data = array(
            'UserID'=> $user_id,
            'Nick'  => $nickname,
            'FaceUrl'=> $image
        );
        $content = json_encode($data);
        $url = "https://console.tim.qq.com/v4/im_open_login_svc/account_import?sdkappid=1600083073&identifier=administrator&usersig={$im_user_sig}&random={$random}&contenttype=json";
        postCurl($url,$content);
    }
    /**
     * 注册IM用户信息
     * @ApiInternal
     * @ApiMethod (POST)
     */
    public function getImUserMessageCount($user_id){
        $tenApi = new TLSSigAPIv2();
        $im_user_sig = $tenApi->genUserSig("administrator");
        $random = random_int(1, 9999);
        $data = array(
            'To_Account'=> $user_id
        );
        $content = json_encode($data);
        $url = "https://console.tim.qq.com/v4/openim/get_c2c_unread_msg_num?sdkappid=1600083073&identifier=administrator&usersig={$im_user_sig}&random={$random}&contenttype=json";
        $res = postCurl($url,$content);
        $res = json_decode($res,true);
        return isset($res['AllC2CUnreadMsgNum']) ? $res['AllC2CUnreadMsgNum'] : 0;
    }
    /**
     * 设置IM用户信息
     * @ApiInternal
     * @ApiMethod (POST)
     */
    public function setImUserInfo($user_id,$nickname = '',$image = ''){
        $tenApi = new TLSSigAPIv2();
        $im_user_sig = $tenApi->genUserSig("administrator");
        $random = random_int(1, 9999);
        $data = array(
            'From_Account'  => $user_id,
            'ProfileItem'   => array(),
        );
        if($nickname){
            $data['ProfileItem'][] = array(
                "Tag"   => "Tag_Profile_IM_Nick",
                "Value" => $nickname
            );
        }
        if($image){
            $data['ProfileItem'][] = array(
                "Tag"   => "Tag_Profile_IM_Image",
                "Value" => $image
            );
        }
        $content = json_encode($data);
        $url = "https://console.tim.qq.com/v4/profile/portrait_set?sdkappid=1600083073&identifier=administrator&usersig={$im_user_sig}&random={$random}&contenttype=json";
        $res = postCurl($url,$content);
        return $res;
    }
   

}
